//
//  ZLPGoodsViewController.m
//  TangYi
//
//  Created by dllo on 15/11/1.
//  Copyright © 2015年 赵连鹏. All rights reserved.
//

#import "ZLPGoodsViewController.h"
#import "ZLPLineCollectionModel.h"
#import "ZLPLineCollectionViewCell.h"
#import "ZLPVerticalCollectionViewCell.h"
#import "ZLPVerticalModel.h"
#import <UIImageView+WebCache.h>
#import "ZLPDetailViewController.h"
#import <MJRefresh.h>
#import <AFNetworking.h>


@interface ZLPGoodsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain) UICollectionView *lineCollection;
@property(nonatomic, retain) NSMutableArray *lineArr;
@property(nonatomic, retain) NSMutableArray *topicArr;
@property(nonatomic, retain) UICollectionView *topicCollection;
@property(nonatomic, assign) NSInteger currectPage;

@end

@implementation ZLPGoodsViewController

- (void)dealloc {
    [_lineArr release];
    [_lineCollection release];
    [_topicArr release];
    [_topicCollection release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    
    [self createLineCollectionView];
    
    [self createTopicCollectionView];
    
    [self createData];
    [self createVerticaData];
    
    self.currectPage = 0;
    [self addFooterRefresh];
    
//    [self isWlan];
    
    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            [self createData];
            [self createVerticaData];
            
            self.currectPage = 0;
            [self addFooterRefresh];
        } else {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];

            
        }
        
    }];
}

- (void)addFooterRefresh {
    
    self.topicCollection.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       
        self.currectPage++;
        [self createRefreshData];
        
    }];
 
}

#pragma mark create方法
- (void)createLineCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(65, 25);
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    
    self.lineCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64 + 25) collectionViewLayout:layout];
    [self.view addSubview:self.lineCollection];
    self.lineCollection.backgroundColor = [UIColor whiteColor];
    self.lineCollection.showsHorizontalScrollIndicator = NO;
    [_lineCollection release];
    
    self.lineCollection.delegate = self;
    self.lineCollection.dataSource = self;
    
    [self.lineCollection registerClass:[ZLPLineCollectionViewCell class] forCellWithReuseIdentifier:@"linecollection"];
}

- (void)createTopicCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 2 - 15, WIDTH / 2 + 13);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.topicCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 37, WIDTH, HEIGHT - 37 - 13 - 37) collectionViewLayout:layout];
    [self.view addSubview:self.topicCollection];
    [_topicCollection release];
    self.topicCollection.showsVerticalScrollIndicator = NO;
    self.topicCollection.backgroundColor = [UIColor whiteColor];
    
    self.topicCollection.delegate = self;
    self.topicCollection.dataSource = self;
    
    [self.topicCollection registerClass:[ZLPVerticalCollectionViewCell class] forCellWithReuseIdentifier:@"topic"];
    
    
}

- (void)createData {
    
    NSString *strURL = @"http://open3.bantangapp.com/category/list";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求方式
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = @"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.1&track_device_info=iPhone6%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    // 把数据添加到请求里
    [request setHTTPBody:bodyData];
    // 建立连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.lineArr = [NSMutableArray array];
            self.lineArr = [ZLPLineCollectionModel baseModelByArr:dic[@"data"]];
            
            [self.lineCollection reloadData];
        } else {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
        }
        
    }];
    

}
- (void)createVerticaData {
    // 垂直collectionView的数据请求
    NSString *verticalURL = @"http://open3.bantangapp.com/product/list";
    NSURL *vertical = [NSURL URLWithString:verticalURL];
    NSMutableURLRequest *verticalRequest = [NSMutableURLRequest requestWithURL:vertical];
    [verticalRequest setHTTPMethod:@"POST"];
    NSString *verticalStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&category=%@&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=f21c227a3e05fa0f8f5fa3eed7f40e0c&os_versions=9.1&page=0&pagesize=20&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.numID];
    NSData *verticalData = [verticalStr dataUsingEncoding:NSUTF8StringEncoding];
    [verticalRequest setHTTPBody:verticalData];
    [NSURLConnection sendAsynchronousRequest:verticalRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.topicArr = [NSMutableArray array];
            self.topicArr = [ZLPVerticalModel baseModelByArr:dic[@"data"][@"product"]];
            
            
            [self.topicCollection reloadData];
        } else {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
        }
        
        
    }];

}
- (void)createRefreshData {
    NSString *strURL = @"http://open3.bantangapp.com/product/list";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&category=%@&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=f21c227a3e05fa0f8f5fa3eed7f40e0c&os_versions=9.1&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.numID, self.currectPage];
    NSData *bodyDate = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyDate];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSMutableArray *tempArr = [NSMutableArray array];
        tempArr = [ZLPVerticalModel baseModelByArr:dic[@"data"][@"product"]];
        for (ZLPVerticalModel *tempModel in tempArr) {
            [self.topicArr addObject:tempModel];
        }
        
        
        [self.topicCollection.footer endRefreshing];
        [self.topicCollection reloadData];
        
    }];
}


#pragma mark collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.lineCollection) {
        return self.lineArr.count;
    } else {
        return self.topicArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.lineCollection) {
        ZLPLineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"linecollection" forIndexPath:indexPath];
        
        ZLPLineCollectionModel *model = [[ZLPLineCollectionModel alloc] init];
        model = self.lineArr[indexPath.row];
        cell.backgroundColor = [UIColor whiteColor];
        cell.nameLabel.text = model.name;;
        
        return cell;
    } else {
        
        ZLPVerticalCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"topic" forIndexPath:indexPath];
        
        ZLPVerticalModel *model = [[ZLPVerticalModel alloc] init];
        model = self.topicArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.titleLabel.text = model.title;
        cell.priceLabel.text = model.price;
        
        return cell;
    }

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.lineCollection) {
        
//        ZLPLineCollectionViewCell *cell = (ZLPLineCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath ];;
//        
//        [self updateCollectionViewCellStatus:cell selected:YES];
        
        ZLPLineCollectionModel *model = [[ZLPLineCollectionModel alloc] init];
        model = self.lineArr[indexPath.row];
        self.numID = model.numID;
        [self createVerticaData];
        
        self.title = model.name; 
        
    } else {
        ZLPDetailViewController *detailVC = [[ZLPDetailViewController alloc] init];
        [self.navigationController pushViewController:detailVC animated:YES];
        
        ZLPVerticalModel *model = [[ZLPVerticalModel alloc] init];
        model = self.topicArr[indexPath.row];
        detailVC.url = model.url;
    }
}

-(void)updateCollectionViewCellStatus:(ZLPLineCollectionViewCell *)myCollectionCell selected:(BOOL)selected
{
    
    if (myCollectionCell) {
        myCollectionCell.nameLabel.textColor = [UIColor redColor];
    } else {
        myCollectionCell.nameLabel.textColor = [UIColor blackColor];
    }
    
    
    
    NSLog(@"%@", myCollectionCell.nameLabel.text);
    
}

// cell点击变色
//- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
//// cell点击变色
//- (void)collectionView:(UICollectionView *)colView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([colView isEqual:self.lineCollection]) {
//        ZLPLineCollectionViewCell *cell = [self.lineCollection cellForItemAtIndexPath:indexPath];
//        [cell setBackgroundColor:[UIColor redColor]];
//    } else {
//        ZLPLineCollectionViewCell* cell = [colView cellForItemAtIndexPath:indexPath];
//        [cell setBackgroundColor:[UIColor blackColor]];
//    }
//}

//- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
//    return YES;
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
